//index.js
const ctx = wx.createCanvasContext('shareImg');

Page({
  cdx: 0, // 窗口宽度
  width: 0,
  /**
   * 页面的初始数据
   */
  data: {
    prurl: '',
    str: '最常用',
    defaultImg: '../../images/switch/on.png',
    isChecked: false,
    list: [
      '../../images/switch/on.png',
      '../../images/switch/off.png'
    ]
  },

  // 初始化
  initCanvas(imgUrl) {
    let that = this;
    // console.log("Promise.all", res)
    //主要就是计算好各个图文的位置
    let num = 150;
    // ctx.drawImage(res[0].path, 0, 0, num, num)
    ctx.drawImage(imgUrl, this.cdx, 0, num, num)
    // ctx.rect(this.cdx, 0, num + 1, num + 1)
    // 添加文字
    ctx.setTextAlign('center')
    ctx.setFontSize(20)
    ctx.fillText(that.data.str, that.width, 50)
    ctx.stroke()

    ctx.draw(false, () => {
      wx.canvasToTempFilePath({
        x: this.cdx,
        y: 0,
        width: num,
        height: num,
        destWidth: 960,
        destHeight: 960,
        canvasId: 'shareImg',
        success: function (res) {
          that.setData({
            prurl: res.tempFilePath
          })
          // wx.hideLoading()
        },
        fail: function (res) {
          wx.hideLoading()
        }
      })
    })
  },

  save: function () {
    var that = this;
    if (!that.data.prurl) {
      wx.showToast({
        title: '请先生成专属头像',
      })
      return;
    }
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            }
          }
        })
      }
    })
  },

  generate: function () {
    this.initCanvas(this.data.defaultImg)
  },

  changeStr: function (e) {
    this.setData({
      str: e.detail.value
    })
  },
  checkboxChange: function (e) {
    let isChecked = e.currentTarget.dataset.checked
    if (isChecked == "false" || isChecked == false) {     //即将选中   将其值设为true
      isChecked = true
      this.data.defaultImg = this.data.list[1]
    } else {
      this.data.defaultImg = this.data.list[0]
      isChecked = false;
    }
    this.setData({
      isChecked: isChecked
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取系统信息
    wx.getSystemInfo({
      success: res => {
        // 获取窗口宽高
        this.cdx = (res.windowWidth - 150) / 2
        this.width = res.windowWidth / 2
      }
    })
    this.initCanvas(this.data.defaultImg)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '领取你的专属头像',
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  }
})